package com.mylife.schedule.service.serviceImpl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mylife.pojo.Result;
import com.mylife.pojo.TransferUtils;
import com.mylife.schedule.mapper.ScheduleMapper;
import com.mylife.schedule.service.ScheduleService;
import com.mylife.schedule.vo.NowScheduleVO;
import com.mylife.schedule.vo.params.ScheduleParams;
import com.mylife.schedule.vo.ScheduleVo;
import com.mylife.service.HttpStatus;
import com.mylife.service.ReturnCodes;
import com.mylife.service.ReturnMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 计划本Service实现类
 *
 * @author blueCat
 * @since 2022/3/5
 */
@Service
@Slf4j
public class ScheduleServiceImpl implements ScheduleService {

    @Autowired
    private ScheduleMapper scheduleMapper;

    /**
     * 查询正在进行的计划
     *
     * @param params
     * @return
     */
    @Override
    public NowScheduleVO queryNowSchedule(ScheduleParams params) {
        NowScheduleVO nowScheduleVO = scheduleMapper.queryNowSchedule(params);
        //获取剩余时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (nowScheduleVO != null) {
            try {
                Date parse = sdf.parse(nowScheduleVO.getEndTime());
                long time1 = parse.getTime();
                long time2 = System.currentTimeMillis();
                nowScheduleVO.setLeftTime((int) ((time1 - time2) / 1000));
            } catch (ParseException e) {
                log.error("时间转换错误！");
            }
        }
        return nowScheduleVO;
    }

    /**
     * 查询全部计划类型
     *
     * @return
     */
    @Override
    public List<String> queryScheduleType() {
        return scheduleMapper.queryScheduleType();
    }

    /**
     * 新增计划
     *
     * @param params
     * @return
     */
    @Override
    public Result addSchedule(ScheduleParams params) {
        //获得计划结束时间
        String scheduleStartTime = params.getScheduleStartTime();
        Integer minuteTime = params.getMinuteTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (scheduleStartTime != null && !scheduleStartTime.equals("")) {
            try {
                long startTime = sdf.parse(scheduleStartTime).getTime();
                long endTime = startTime + minuteTime * 60 * 1000;
                String scheduleEndTime = sdf.format(new Date(endTime));
                params.setScheduleEndTime(scheduleEndTime);
            } catch (ParseException e) {
                log.error("时间转换错误！");
            }
        }
        int i = scheduleMapper.addSchedule(params);
        if (i == 1) {
            return Result.setSuccess(HttpStatus.SUCCESS, "添加计划成功！");
        } else {
            return Result.setFail(ReturnCodes.ADD_SCHEDULE_FAIL, ReturnMessage.ADD_SCHEDULE_FAIL);
        }
    }

    /**
     * 查询计划
     *
     * @param params
     * @return
     */
    @Override
    public List<ScheduleVo> querySchedules(ScheduleParams params) {
        //获取查询时间区间
        String startDate = params.getStartDate();
        params.setScheduleStartTime(startDate + " 00:00:00");
        params.setScheduleEndTime(startDate + " 23:59:59");
        //开始查询
        Page<ScheduleVo> page = new Page<>(params.getPageNum(), params.getPageSize());
        //设置默认排序
        params.setOrderByColumn("start_time");
        params.setIsAsc("asc");
        List<ScheduleVo> data = scheduleMapper.querySchedules(page, params);
        //回填序号
        int index = 1;
        for (ScheduleVo datum : data) {
            datum.setIndex(index++);
            //回填完成状态
            if (datum.getIsFinish().equals(0)) {
                datum.setFinishStatus("未完成");
            } else if (datum.getIsFinish().equals(1)) {
                datum.setFinishStatus("完成");
            }
        }
        //获取total
        long total = page.getTotal();
        if (data.size() > 0) {
            data.get(0).setTotal(total);
        }
        return data;
    }

    /**
     * 删除计划
     *
     * @param id
     * @return
     */
    @Override
    public Result deleteSchedule(Integer id) {
        Integer number = scheduleMapper.deleteSchedule(id);
        if (number == 1) {
            return Result.setSuccess(HttpStatus.SUCCESS, "删除成功！");
        } else {
            return Result.setFail(ReturnCodes.SCHEDULE_DELETE_FAIL, ReturnMessage.SCHEDULE_DELETE_FAIL);
        }
    }

    /**
     * 改变完成状态
     *
     * @param id
     * @param isFinish
     * @return
     */
    @Override
    public Result changeFinishStatus(Integer id, Integer isFinish) {
        Integer number = scheduleMapper.changeFinishStatus(id, isFinish);
        if (number == 1) {
            return Result.setSuccess(HttpStatus.SUCCESS, "修改成功！");
        } else {
            return Result.setFail(ReturnCodes.FINISH_STATUS_FAIL, ReturnMessage.FINISH_STATUS_FAIL);
        }
    }

    /**
     * 查询单条计划
     *
     * @param id
     * @return
     */
    @Override
    public ScheduleVo queryOneSchedule(Integer id) {
        ScheduleVo scheduleVo = scheduleMapper.queryOneSchedule(id);
        //处理startDate和scheduleStartTime以及minuteTime
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date startTime = sdf.parse(scheduleVo.getStartTime());
            Date endTime = sdf.parse(scheduleVo.getEndTime());
            //获取minuteTime
            Integer minuteTime = (int) ((endTime.getTime() - startTime.getTime()) / (1000 * 60));
            scheduleVo.setMinuteTime(minuteTime);
            //获取开始日期
            scheduleVo.setStartDate(scheduleVo.getStartTime().split(" ")[0]);
            //获取计划开始时间
            scheduleVo.setScheduleStartTime(scheduleVo.getStartTime().split(" ")[1]);
        } catch (ParseException e) {
            log.error("时间转换错误！");
        }
        return scheduleVo;
    }

    /**
     * 修改计划
     *
     * @param params
     * @return
     */
    @Override
    public Result updateSchedule(ScheduleParams params) {
        //获得计划结束时间
        String scheduleStartTime = params.getScheduleStartTime();
        Integer minuteTime = params.getMinuteTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            long startTime = sdf.parse(scheduleStartTime).getTime();
            long endTime = startTime + minuteTime * 60 * 1000;
            String scheduleEndTime = sdf.format(new Date(endTime));
            params.setScheduleEndTime(scheduleEndTime);
        } catch (ParseException e) {
            log.error("时间转换错误！");
        }
        Integer number = scheduleMapper.updateSchedule(params);
        if (number == 1) {
            return Result.setSuccess(HttpStatus.SUCCESS, "修改成功！");
        } else {
            return Result.setFail(ReturnCodes.SCHEDULE_UPDATE_FAIL, ReturnMessage.SCHEDULE_UPDATE_FAIL);
        }
    }

    /**
     * 增加计划类型
     *
     * @param scheduleType
     * @return
     */
    @Override
    public Result addScheduleType(String scheduleType) {
        int i = scheduleMapper.addScheduleType(scheduleType);
        if (i == 1) {
            return Result.setSuccess(HttpStatus.SUCCESS, "添加计划类型成功！");
        } else {
            return Result.setFail(ReturnCodes.ADD_SCHEDULE_TYPE_FAIL, ReturnMessage.ADD_SCHEDULE_TYPE_FAIL);
        }
    }

    /**
     * 统计计划内容
     *
     * @param params
     * @return
     */
    @Override
    public List<ScheduleVo> queryCountSchedule(ScheduleParams params) {
        //处理timeRange获得startTime和endTime
        if (params.getTimeRange() != null && params.getTimeRange().size() > 1) {
            List<String> timeRange = params.getTimeRange();
            params.setScheduleStartTime(timeRange.get(0) + " 00:00:00");
            params.setScheduleEndTime(timeRange.get(1) + " 23:59:59");
        } else {
            List<String> timeRange = params.getTimeRange();
            params.setScheduleStartTime(timeRange.get(0) + " 00:00:00");
            params.setScheduleEndTime(timeRange.get(0) + " 23:59:59");
        }
        List<ScheduleVo> data = scheduleMapper.queryCountSchedule(params);
        //回填完成比例
        if (data.size() > 0) {
            DecimalFormat df = new DecimalFormat("0.00");
            List<ScheduleVo> data2 = scheduleMapper.queryFinishTime(params);
            for (ScheduleVo datum : data) {
                for (ScheduleVo scheduleVo : data2) {
                    if (datum.getScheduleType().equals(scheduleVo.getScheduleType())) {
                        datum.setFinishPercentage(df.format((Double.parseDouble(scheduleVo.getSumTime()) / Double.parseDouble(datum.getSumTime())) * 100) + "%");
                    }
                }
            }
            //获取总时间
            int totalTime = 0;
            for (ScheduleVo datum : data) {
                if (datum.getFinishPercentage() == null || datum.getFinishPercentage().equals("")) {
                    datum.setFinishPercentage("0.00%");
                }
                totalTime += Integer.parseInt(datum.getSumTime());
            }
            data.get(0).setTotalTime(TransferUtils.transferMinute(totalTime));
            for (ScheduleVo datum : data) {
                //设置类型占比
                datum.setPercentage(df.format((Double.parseDouble(datum.getSumTime()) / (double)totalTime) * 100) + "%");
                //转换时间
                datum.setSumTime(TransferUtils.transferMinute(Integer.parseInt(datum.getSumTime())));
            }
        }
        return data;
    }
}
